1.1 Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
In [27]:
# from IPython.core.debugger import set_trace
def has_unique_characters(str=''):
'''
Checks if a string has all unique characters
>>> has_unique_characters('abc')
True
>>> has_unique_characters()
True
>>> has_unique_characters('abac')
False
'''
# 1/ time: 1.74 µs ± 14.5 ns
# unique_chars = dict.fromkeys(str,1)
# return len(unique_chars)==len(str)
# 2/ time: 1.04 µs ± 7.39 ns using dictionary
# unique_chars ={}
# for char in str:
# if char in unique_chars:
# return False
# unique_chars[char]=1
# return True
# 3/ 1.4 µs ± 19.1 ns using a set
# char_set =set()
# for char in str:
# if char in char_set:
# return False
# char_set.add(char)
# return True
# 4/ 1.38 µs ± 8 ns using a bit vector
bit_vector =0b0
pos_a=ord('a')
# set_trace()
for char in str:
pos_char=ord(char)-pos_a
# print('vec:{:0>35b}'.format(bit_vector))
# print('pos:{:0>35b}'.format(1 << pos_char))
if bit_vector & (1 << pos_char):
return False
bit_vector |= (1 << pos_char)
return True
# print(has_unique_characters('qwertyuuidfsdgsg'))
%timeit has_unique_characters('qwertyuuidfsdgsg')
# import doctest; doctest.testmod()
1.2 Check Permutation: Given two strings,write a method to decide if one is a permutation of the other.
In [37]:
# def isPermutations(s1,s2):
# len1 = len(s1)
# len2 = len(s2)
# if len1 != len2:
# return False
# ss1=sorted(s1)
# ss2=sorted(s2)
# for i in range(0,len1):
# if ss1[i] != ss2[i]:
# return False
# return True
def isPermutations(s1,s2):
if len(s1) != len(s2):
return False
char_counts={}
# fill it
for c in s1:
char_counts[c] = char_counts.get(c,0) +1
# empty it
for c in s2:
char_counts[c] = char_counts.get(c,0) -1
# check if all are 0
for c in char_counts:
if char_counts[c] != 0:
return False
return True
print( isPermutations('abcdefffgh', 'dcabefghff') )
In [52]:
Out[52]: